package Action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;

import Bean.CommentBean;
import Utils.Common;





public class Comment{
	public String load(HttpServletRequest request, Connection conn){
		String xml="";
		String newsid=request.getParameter("newsid");
		String sql = "";
		if(newsid==null || newsid.equals(""))
			sql = "SELECT * FROM comment INNER JOIN userinfo ON comment.AccountId=userinfo.accountid ORDER BY CreatedDate DESC LIMIT 200";
		else
			sql = "SELECT * FROM comment INNER JOIN userinfo ON comment.AccountId=userinfo.accountid AND comment.NewsId='"+newsid+"' ORDER BY CreatedDate DESC LIMIT 200";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				CommentBean cm = new CommentBean();
				cm.setId(rs.getString("CommentId"));
				cm.setItemid(rs.getString("NewsId"));
				cm.setName(rs.getString("lastname")+" "+rs.getString("firstname"));
				cm.setTime(rs.getString("CreatedDate"));
				cm.setContent(rs.getString("Comment"));
				cm.setAccountid(rs.getString("comment.AccountId"));
				cm.setPic(rs.getString("comment.AccountId"));
				xml+=cm.makeXML();
			}
			return Common.makeSuccessXML(xml);
		}catch (Exception e) {
			e.printStackTrace();
			return Common.makeErrorXML(e.getMessage());
		}finally{
			if (stmt != null) {
				try {
					stmt.close();
				} catch (Exception e) {
				}
			}
			if (rs != null) {
				try {
					rs.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	public String delete(HttpServletRequest request, Connection conn){
		String id=request.getParameter("id");
		PreparedStatement stmt = null;
		try{
			String sql = "DELETE FROM comment WHERE CommentId=?";
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, id);
			stmt.executeUpdate();
			return Common.makeSuccessXML();
		}catch (Exception e) {
			return Common.makeErrorXML(e.getMessage());
		}finally{
			if (stmt != null) {
				try {
					stmt.close();
				} catch (Exception e) {
				}
			}
		}
	}
}